package com.spx.chapter06;

import com.spx.chapter05.pojo.Event;
import com.spx.util.SampleDataUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

/**
 * create by undeRdoG on  2022-05-02  19:26
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class WindowTest {

    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<Event> dataSource = env.fromCollection(SampleDataUtil.getSample())
                // 设置watermark
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<Event>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.timestamp;
                                    }
                                })
                );


        /*
        *  事件时间窗口
        * */

        WindowedStream<Event, String, TimeWindow> window1 = dataSource
                .keyBy(data -> data.user)
                // 滚动事件时间窗口，设置为1h
                .window(TumblingEventTimeWindows.of(Time.hours(1)));


        dataSource.keyBy(data -> data.user)
                // 滑动事件时间窗口
                .window(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(5)));


        dataSource.keyBy(data -> data.user)
                // 事件时间会话窗口
                .window(EventTimeSessionWindows.withGap(Time.seconds(10L)));


        /*
        * 计数窗口
        * */
        dataSource.keyBy(data -> data.user)
                // 滚动计数窗口
                .countWindow(10L);

        dataSource.keyBy(data -> data.user)
                // 滑动计数窗口
                .countWindow(10L,5L);



    }
}
